<template>
  <div class="app">
    <el-card class="box-card">
      <span>编辑信息</span>
      <el-divider></el-divider>

      <div class="formclass">
        <el-form ref="form" :model="form" label-width="80px">
          <div class="badyclass">
            <el-form-item label="菜名">
              <el-input v-model="form.name" style="width: 240px"></el-input>
            </el-form-item>
            <el-form-item label="图片" placeholder="image">
              <img :src="form.image" class="imgs" />
              <!-- 文件上传按钮 -->
              <el-button
                type="primary"
                icon="el-icon-upload"
                @click="imagecropperShow = true"
              >
              </el-button>
              <!--
                v-show：是否显示上传组件
                :key：类似于id，如果一个页面多个图片上传控件，可以做区分
                :url：后台上传的url地址
                @close：关闭上传组件
                @crop-upload-success：上传成功后的回调 -->
              <image-cropper
                v-show="imagecropperShow"
                :width="240"
                :height="120"
                :key="imagecropperKey"
                :url="'/oss/uploadImgFile'"
                field="file"
                @close="closeImage"
                @crop-upload-success="cropSuccess"
              />
            </el-form-item>
            <el-form-item label="归属类别">
              <el-select
                v-model="form.categoryId"
                placeholder="请选择父级菜单"
                style="width: 240px"
                clearable
              >
                <el-option
                  :value="form.categoryId"
                  :label="form.cateName"
                  style="height: 150px; overflow: auto; background-color: #fff"
                >
                  <el-tree
                    :data="arr"
                    :props="{ children: 'childMenus', label: 'name' }"
                    @node-click="handleNodeClick"
                  ></el-tree>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="价格">
              <el-input v-model="form.price" style="width: 240px"></el-input>
            </el-form-item>

            <el-form-item label="描述">
              <el-input
                v-model="form.description"
                style="width: 240px"
              ></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择" clearable>
                <el-option label="禁用" value="0"></el-option>
                <el-option label="启用" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="轮播顺序">
              <el-input-number
                v-model="form.sort"
                @change="handleChange"
                :min="1"
                :max="10"
                label="描述文字"
              ></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">确定</el-button>
              <el-button>取消</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import ImageCropper from "../../components/ImageCropper";
import PanThumb from "../../components/PanThumb";
import { categoryTree } from "../../api/category";
import { selectById } from "../../api/category";
import { getUpdateById, getInsert } from "../../api/category";
export default {
  components: { ImageCropper, PanThumb },
  data() {
    return {
      form: {
        id: "",
        name: "",
        image: "",
        cateName: "",
        categoryId: "",
        price: "",
        description: "",
        status: "",
        sort: "",
        sales: "",
        comment: "",
        ingredients: "",
        taste: "",
        weight: "",
        describe: "",
      },
      category_id: "",
      category_name: "",
      //储存修改的分类id
      cateid: "",
      image: "",
      arr: [],
      flag: false,
      //弹窗
      dialogVisible: false,
      imagecropperShow: false, // 是否显示上传组件
      imagecropperKey: 0, // 上传组件id
      field101Action: "https://jsonplaceholder.typicode.com/posts/",
      field101fileList: [],
    };
  },
  methods: {
    onSubmit() {
      if (this.flag) {
        //修改
        this.updatedish();
      } else {
        //新增
        this.adddish();
      }
    },
    //修改
    async updatedish() {
      var $this = this;
      this.form.categoryId = this.category_id;
      console.log(this.form);
      let result = await getUpdateById(this.form);
      if (result.data.code === 200) {
        //弹出消息
        $this.$message({
          message: "修改成功",
          type: "success",
          duration: 2000,
        });
        this.$router.push("/category");
        //清空数据
        $this.form = {};
      }
    },
    //新增
    async adddish() {
      var $this = this;
      this.form.categoryId = this.category_id;

      let result = await getInsert(this.form);
      if (result.data.code === 200) {
        //弹出消息
        $this.$message({
          message: "新增成功",
          type: "success",
          duration: 2000,
        });
        this.$router.push("/category");
        //清空数据
        $this.form = {};
      }
    },
    //内侧tree树形结构
    async getcategoryTree() {
      let result = await categoryTree();
      this.arr = result.data.tree;
    },
    field101BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error("文件大小超过 2MB");
      }
      let isAccept = new RegExp("image/*").test(file.type);
      if (!isAccept) {
        this.$message.error("应该选择image/*类型的文件");
      }
      return isRightSize && isAccept;
    },
    // 上传成功后的回调函数
    cropSuccess(data) {
      var oldImage = this.form.image;
      this.imagecropperShow = false;
      this.form.image = data.url;
      console.log(this.form.image);
      // 上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1;
      //上传成功之后删除之前的头像
    },

    // 关闭上传组件
    closeImage() {
      this.imagecropperShow = false;
      // 上传失败后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1;
    },
    //删除上传之前的图片
    async deleteAvatar(oldImage) {
      const { data } = await deleteImgFile(oldImage);
    },
    handleChange(sort) {
      console.log(sort);
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.dialogVisible = false;
          done();
        })
        .catch((_) => {});
    },
    handleNodeClick(data) {
      this.category_id = data.id;
      this.$set(this.form, "category_id", data.id);
      this.form.cateName = data.name;
    },
    //通过id查询
    async getselectbyid(id) {
      let result = await selectById(id);
      this.form = result.data.Dish;
      console.log(this.form);
    },
    selct(id) {
      this.getselectbyid(id);
    },
    treeuodate() {
      this.dialogVisible = false;
    },
  },
  created() {
    var id = this.$route.params.id;
    if (id != null) {
      this.selct(id);

      this.flag = true;
    }

    this.getcategoryTree();
  },
};
</script>

<style lang="less" scoped>
.app {
  width: 100%;
  height: 100vh;
}
.imgs {
  width: 200px;
  height: 88px;
}
</style>